package dao;
import com.mysql.cj.jdbc.MysqlDataSource;

import java.sql.*;

//通过这个类，把数据库的建立连接的逻辑进行封装
public class DBUtil {
    private static volatile MysqlDataSource dataSource = null;
    private static MysqlDataSource getDataSource() {
        if (dataSource == null) {
            synchronized (DBUtil.class) {
                if (dataSource == null) {
                    dataSource = new MysqlDataSource();
                    dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/blog_system?useUnicode=true&characterEncoding=utf8");
                    dataSource.setUser("root");
                    dataSource.setPassword("354684");
                }
            }
        }
        return dataSource;
    }
    //提供一个方法，和数据库建立连接
    public static Connection getConnection() {
        try{
            return getDataSource().getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet) {
        if(resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
